package com.schoolvisitors.repository;

import com.schoolvisitors.entity.User;
import com.schoolvisitors.enums.UserStatusEnum;
import jakarta.persistence.LockModeType;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
//    boolean existsByUsername(String username);
    boolean existsByPhone(String phone);
    boolean existsByIdNumber(String idNumber);

    // 使用悲观写锁
    @Query("SELECT u FROM User u WHERE u.id = :id")
    @Lock(LockModeType.PESSIMISTIC_WRITE)
    Optional<User> findByIdWithLock(@Param("id") Long id);

    User findByWechatUserId(String wechatUserId);

    Page<User> findByStatus(UserStatusEnum status, Pageable pageable);

    Page<User> findByRealNameContaining(String realName, Pageable pageable);



    boolean existsByIdNumberAndIdNot(String idNumber, Long id);

    boolean existsByPhoneAndIdNot(@Size(max = 11) @NotNull String phone, Long id);
}
